<template>
  <view class="app-quickly-login">
    <view class="app-quickly-login-btn" @click="onWXLogin">快捷登录</view>
  </view>
</template>
<script setup >
import {  onBeforeUnmount, onBeforeMount, defineEmits } from "vue";
import { ref, defineProps, getCurrentInstance, watch } from "vue";
import { loginByQuicklyAPi, checkIsExistPhoneApi } from "@/api/login/index.js";
import { customNav } from "@/utils/customNav";
const props = defineProps({
  agree: {
    type: Boolean,
  },
});
const emits = defineEmits(["on-click","on-success"]);
const { proxy } = getCurrentInstance();
const loginInfo = ref({});
const codeData = ref("");
const num = ref(0);
watch(
  codeData,
  (newVal, oldVal) => {
    if (newVal !== oldVal && newVal !== "") {
      loginByQuickly();
    }
  },
  {
    immediate: true,
  }
);
const onWXLogin = () => {
  if (props.agree) {
    window.mobile.jsCallWxLogin();
  } else {
    proxy.modal.msg("请阅读《用户服务协议》和《隐私政策》并勾选");
  }
};
const callLoginChange = () => {
  if (typeof (window.callLoginData) !== "undefined") {
    loginInfo.value = JSON.parse(window.callLoginData);
    codeData.value = loginInfo.value.code;
  }
};

const loginByQuickly = async () => {
  await uni.showLoading({
    title: "登录中...",
  });
  const params = {
    client_id: "huatai",
    client_secret: "waytale",
    auth_type: "wx",
    code: codeData.value,
    wx_login_type: "1",
    grant_type: "password",
  };
  const res = await loginByQuicklyAPi(params);
  const { access_token } = res;

  if (access_token) {
    uni.hideLoading();
    uni.setStorageSync("token", access_token);
    checkIsExistPhone();
    emits("on-success",false)
  }
};
const checkIsExistPhone = async () => {
  const res = await checkIsExistPhoneApi();
  const { success } = res || {};
  if (success) {
    await uni.showToast({
      title: "需要绑定手机号",
      duration: 1000,
    });
    customNav("binding");
  } else {
    await uni.showToast({
      title: "登录成功",
      duration: 2000,
    });
    await uni.switchTab({
      url: "/pages/index/index",
    });
  }
};
window.addEventListener("callLogin", callLoginChange, true);
onBeforeUnmount(() => {
  // 移除监听事件
  window.removeEventListener("callLogin", callLoginChange);
});
</script>

<style scoped lang=less>
.app-quickly-login {
  width: 80vw;
  margin-top: 40rpx;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
  align-items: center;
  &-text {
    font-weight: 400;
    font-size: 23rpx;
    color: @color-origin-white;
  }
  &-btn {
    width: 80vw;
    margin-top: 29rpx;
    background-color: @color-green;
    background-repeat: no-repeat;
    font-size: @font-size-31;
    font-weight: 400;
    border: none;
    text-align: center;
    color: @color-origin-white;
    height: 78rpx;
    line-height: 78rpx;
    border-radius: 13rpx;
  }
}

button::after {
  border: none;
}
</style>
